"""
系统监控API路由
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from models.database import User
from api.auth import get_current_user, get_current_admin
from core.database import get_db
from core.logger import api_logger
from services.system_monitor import SystemMonitorService
from services.metrics_storage import MetricsStorageService
from core.config import get_settings
router = APIRouter()

settings = get_settings()


@router.get("/metrics")
async def get_system_metrics_public(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前系统监控指标（所有用户可访问）"""
    try:
        metrics = SystemMonitorService.get_cached_metrics()
        return {
            "cpu_percent": metrics["cpu_percent"],
            "memory_percent": metrics["memory_percent"],
            "disk_percent": metrics["disk_percent"],
            "uptime": metrics["uptime"],
            "status": SystemMonitorService.get_system_status(),
            "formatted_uptime": SystemMonitorService.format_uptime(metrics["uptime"]),
            "timestamp": metrics["timestamp"].isoformat()
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/metrics/simple")
async def get_system_metrics_simple(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取简化的系统监控指标（用于仪表板）"""
    try:
        metrics = SystemMonitorService.get_cached_metrics()  
        return {
            "cpu": metrics["cpu_percent"],
            "memory": metrics["memory_percent"],
            "disk": metrics["disk_percent"],
            "status": SystemMonitorService.get_system_status(),
            "formatted_uptime": SystemMonitorService.format_uptime(metrics["uptime"]),
            "timestamp": metrics["timestamp"].isoformat()
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/simple"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/metrics/config")
async def get_metrics_config(
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """获取系统监控配置（管理员权限）"""
    try:
        config = MetricsStorageService.get_metrics_config()
        return {
            "success": True,
            "config": config
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/config"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/metrics/history")
async def get_metrics_history(
    hours: int = Query(24, ge=1, le=168, description="查询小时数（1-168小时）"),
    limit: Optional[int] = Query(None, ge=1, le=1000, description="返回记录数限制"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取历史监控数据"""
    try:
        if not MetricsStorageService.is_metrics_enabled():
            return {
                "success": False,
                "message": "系统监控数据保存功能未启用",
                "data": []
            }
        
        history = MetricsStorageService.get_metrics_history(hours=hours, limit=limit)
        return {
            "success": True,
            "data": history,
            "total": len(history),
            "hours": hours
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/history"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/metrics/summary")
async def get_metrics_summary(
    hours: int = Query(24, ge=1, le=168, description="统计小时数（1-168小时）"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取监控数据统计摘要"""
    try:
        if not MetricsStorageService.is_metrics_enabled():
            return {
                "success": False,
                "message": "系统监控数据保存功能未启用",
                "data": {}
            }
        
        summary = MetricsStorageService.get_metrics_summary(hours=hours)
        return {
            "success": True,
            "data": summary,
            "hours": hours
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/summary"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.get("/metrics/latest")
async def get_latest_metrics(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取最新保存的监控数据"""
    try:
        if not MetricsStorageService.is_metrics_enabled():
            return {
                "success": False,
                "message": "系统监控数据保存功能未启用",
                "data": None
            }
        
        latest = MetricsStorageService.get_latest_metrics()
        return {
            "success": True,
            "data": latest
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/latest"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


@router.post("/metrics/cleanup")
async def cleanup_metrics(
    days: int = Query(30, ge=1, le=365, description="清理天数（1-365天）"),
    current_user: User = Depends(get_current_admin),
    db: Session = Depends(get_db)
):
    """清理监控数据（管理员权限）"""
    try:
        if not MetricsStorageService.is_metrics_enabled():
            return {
                "success": False,
                "message": "系统监控数据保存功能未启用",
                "deleted_count": 0
            }
        
        deleted_count = MetricsStorageService.cleanup_old_metrics(days=days)
        return {
            "success": True,
            "message": f"已清理 {deleted_count} 条 {days} 天前的监控数据",
            "deleted_count": deleted_count
        }
    except Exception as e:
        api_logger.log_error(e, {"endpoint": "/system/metrics/cleanup"})
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Internal server error"
        )


# 导出路由器
system_router = router